package com.pro.control;

import com.pro.common.GuavaCommon;
import com.pro.entity.*;
import com.pro.service.ProductService;
import com.pro.utils.DateUtils;
import com.pro.utils.GuavaUtils;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

@Controller
@RequestMapping("/Product")
public class ProductController {
    @Autowired
    private ProductService productService;
    /* 刘弘禹
     * 2021/11/3
     * 查询商品
     * */
    @RequestMapping("/queryProduct")
    @ResponseBody
    public JsonData queryProduct(Product product){
        List<Product> products = productService.queryProduct(product);
        return products != null?JsonData.buildSuccess(products):JsonData.buildError("服务器错误");
    }
    /* 刘弘禹
     * 2021/11/3
     * 查询商品分类 化树
     * */
    @RequestMapping("/productClass")
    @ResponseBody
    public JsonData productClass(){
        //通过key获取内存中数据
        Object ifPresent = GuavaUtils.getTenCacheBuild().getIfPresent(String.valueOf(GuavaCommon.Commodity));
        //判断数据是否存在
        if(ifPresent != null){
            //存在直接使用缓存中数据
            return ifPresent != null?JsonData.buildSuccess(ifPresent):JsonData.buildError("服务器错误");
        }else{
            //不存在将数据存入缓存
            GuavaUtils.getTenCacheBuild().put(String.valueOf(GuavaCommon.Commodity),productService.productClass());
        }
        //不存在时是去数据库查询
        return productService.productClass() != null?JsonData.buildSuccess(productService.productClass()):JsonData.buildError("服务器错误");
    }
    /* 刘弘禹
     * 2021/11/4
     * 查询商品分类  下拉框
     * */
    @RequestMapping("/productCategroys")
    @ResponseBody
    public JsonData productCategroys(){
        List<ProductCategroy> products = productService.productClass();
        return productCategroysSun(products) != null?JsonData.buildSuccess(productCategroysSun(products)):JsonData.buildError("服务器错误");
    }

    private List<ProductCategroy> productCategroysSun(List<ProductCategroy> productCategroys){
        for (int i = 0; i<productCategroys.size();i++ ){
            for (int k = 1; k<productCategroys.size();k++ ){
                if(productCategroys.get(i).getCategroyId() == productCategroys.get(k).getParentId()){
                    productCategroys.remove(productCategroys.get(i));
                    productCategroysSun( productCategroys);
                }
            }
        }
        return productCategroys;
    }

    /* 刘弘禹
     * 2021/11/3
     * 修改上架下架状态
     * */
    @RequestMapping("/updateState")
    @ResponseBody
    public JsonData updateStatus(Integer state,Integer id){
        Boolean aBoolean = productService.updateState(state,id);
        return aBoolean != null?JsonData.buildSuccess(aBoolean):JsonData.buildError("服务器错误");
    }

    /**
     * @ClassName NavigationBarData
     * @Author 刘弘禹
     * @Date 2021/11/6
     */

    @RequestMapping("/updateProduct")
    @ResponseBody
    public JsonData updateProduct(Product product){
        Boolean aBoolean = productService.updateProduct(product);
        return aBoolean != null?JsonData.buildSuccess(aBoolean):JsonData.buildError("服务器错误");
    }

    /**
     * @ClassName NavigationBarData
     * @Author 刘弘禹
     * @Date 2021/11/6
     */
    @RequestMapping("/delProduct")
    @ResponseBody
    public JsonData delProduct(Integer productId){
        Boolean aBoolean = productService.delProduct(productId);
        return aBoolean != null?JsonData.buildSuccess(aBoolean):JsonData.buildError("服务器错误");
    }

    /**
     * @ClassName NavigationBarData
     * @Author 刘弘禹
     * @Date 2021/11/6
     */
    @RequestMapping("/addProduct")
    @ResponseBody
    public JsonData addProduct(Product product){
        Boolean aBoolean = productService.addProduct(product);
        return aBoolean != null?JsonData.buildSuccess(aBoolean):JsonData.buildError("服务器错误");
    }

    //删除商品分类
    @RequestMapping("/delProductCaegory")
    @ResponseBody
    public JsonData delProductCaegory(Integer categoryId){
        //清除缓存
        GuavaUtils.getTenCacheBuild().invalidate(String.valueOf(GuavaCommon.Commodity));
        Boolean aBoolean = productService.delProductCaegory(categoryId);
        return aBoolean != null?JsonData.buildSuccess(aBoolean):JsonData.buildError("服务器错误");
    }

    //修改商品分类
    @RequestMapping("/updateProductCaegory")
    @ResponseBody
    public JsonData updateProductCaegory(Integer categoryId, String title){
        GuavaUtils.getTenCacheBuild().invalidate(String.valueOf(GuavaCommon.Commodity));
        Boolean aBoolean = productService.updateProductCaegory(categoryId, title);
        return aBoolean != null?JsonData.buildSuccess(aBoolean):JsonData.buildError("服务器错误");
    }

    //添加商品审核记录
    @RequestMapping("/addProductCaegory")
    @ResponseBody
    public JsonData addProductCaegory(ProductCategroy productCategroy){
        GuavaUtils.getTenCacheBuild().invalidate(String.valueOf(GuavaCommon.Commodity));
        productCategroy.setCreateDate(new Date());
        Boolean aBoolean = productService.addProductCaegory(productCategroy);
        return aBoolean != null?JsonData.buildSuccess(aBoolean):JsonData.buildError("服务器错误");
    }

    //添加商品分类
    @RequestMapping("/addProductJournal")
    @ResponseBody
    public JsonData addProductJournal(NavigationBarData navigationBarData){
        navigationBarData.setCreateTime(new Date());
        navigationBarData.setDictType("12");
        Boolean aBoolean = productService.addProductJournal(navigationBarData);
        return aBoolean != null?JsonData.buildSuccess(aBoolean):JsonData.buildError("服务器错误");
    }

    //查询商品日志
    @RequestMapping("/getNavIgation")
    @ResponseBody
    public JsonData getNavIgation(NavigationBarData navigationBarData){
        List<NavigationBarData> navIgation = productService.getNavIgation(navigationBarData);
        return navIgation != null?JsonData.buildSuccess(navIgation):JsonData.buildError("服务器错误");
    }

    //查询商品审核详情
    @RequestMapping("/queryCourseRecord")
    @ResponseBody
    public JsonData queryCourseRecord(Integer id){
        List<CourseRecordPlus> courseRecords = productService.queryCourseRecord(id);
        return courseRecords != null?JsonData.buildSuccess(courseRecords):JsonData.buildError("服务器错误");
    }

    //添加商品操作日志
    @RequestMapping("/addProductOperationRecord")
    @ResponseBody
    public JsonData addProductOperationRecord(JsLog dictData){
        dictData.setCreateDate(new Date());
        Boolean aBoolean = productService.addProductOperationRecord(dictData);
        return aBoolean != null?JsonData.buildSuccess(aBoolean):JsonData.buildError("服务器错误");
    }


    /**
     * @ClassName Product
     * @Author 谭金诚
     * @Date 2021/11/11
     */
    //导入excel表格
    @RequestMapping(value = "/importExcel")
    @ResponseBody
    public JsonData importExcel(MultipartFile file){
        Product product = new Product();

        String originalFilename = file.getOriginalFilename();

        InputStream in = null;
        try {
            //将file转InputStream
            in = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        /*if (originalFilename.substring(originalFilename.indexOf(".")) == "xlsx"){
            //将InputStream转XLS对象（即表格对象）
            XSSFWorkbook xssfWorkbook = null;
        }
        if (originalFilename.substring(originalFilename.indexOf("." )) == "xls"){
            HSSFWorkbook hssfWorkbook = null;
        }*/
        XSSFWorkbook xssfWorkbook = null;
        try {
            xssfWorkbook = new XSSFWorkbook(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取表格的第一页
        Sheet xssfSheet = xssfWorkbook.getSheetAt(0);
        //获取该页有多少数据
        int rowNum= xssfSheet.getLastRowNum();

        Boolean aBoolean = false;

        for(int i=1; i <= rowNum; i++){
            //获取当前行
            Row xssfRow = xssfSheet.getRow(i);
            //以此获得该行的所有单元格
            String productCode = xssfRow.getCell(1).toString();
            String categoryId = xssfRow.getCell(2).toString();
            String recommend = xssfRow.getCell(3).toString();
            String  discount = xssfRow.getCell(4).toString();
            String ensure = xssfRow.getCell(5).toString();
            String productName = xssfRow.getCell(6).toString();
            String searchKeywords = xssfRow.getCell(7).toString();
            String  mainImage = xssfRow.getCell(8).toString();
            String currentpriceProduct = xssfRow.getCell(9).toString();
            String originalpriceProduct = xssfRow.getCell(10).toString();
            String productDescription = xssfRow.getCell(11).toString();
            String hits = xssfRow.getCell(12).toString();
            String productSate = xssfRow.getCell(13).toString();
            String createId = xssfRow.getCell(14).toString();
            String createDate = xssfRow.getCell(15).toString();
            String updateId = xssfRow.getCell(16).toString();
            String updateDate = xssfRow.getCell(17).toString();
            String productLabel = xssfRow.getCell(18).toString();

            //将数据写入实体类
            product.setProductCode(DateUtils.StrisInt(productCode));
            product.setCategoryId(DateUtils.StrisInt(categoryId));
            product.setRecommend(DateUtils.StrisInt(recommend));
            product.setDiscount(DateUtils.StrisInt(discount));
            product.setEnsure(DateUtils.StrisInt(ensure));
            product.setProductName(productName);
            product.setSearchKeywords(searchKeywords);
            product.setMainImage(mainImage);
            product.setCurrentpriceProduct(DateUtils.StrDou(currentpriceProduct));
            product.setOriginalpriceProduct(DateUtils.StrDou(originalpriceProduct));
            product.setProductDescription(productDescription);
            product.setHits(DateUtils.StrisInt(hits));
            product.setProductSate(DateUtils.StrisInt(productSate));
            product.setCreateId(createId);
            product.setCreateDate(DateUtils.transString(createDate));
            product.setUpdateId(updateId);
            product.setUpdateDate(DateUtils.transString(updateDate));
            product.setProductLabel(productLabel);

            System.err.println(product);
            //将实体类插入数据库
            aBoolean = productService.addExcel(product);
        }
        return aBoolean != false ? JsonData.buildSuccess(aBoolean) : JsonData.buildError("服务端错误");
    }
}
